import { useState, useRef } from 'react';
import ReactEcharts from 'echarts-for-react';
import { Select, Button, Tooltip, Modal } from 'antd';
import RPATable from './Table';
import { Download, Maximize } from 'lucide-react';
import * as XLSX from 'xlsx';

function JsonToExcel(value: string) {
  const workbook = XLSX.utils.book_new();
  const ws = XLSX.utils.json_to_sheet(JSON.parse(value));
  XLSX.utils.book_append_sheet(workbook, ws, 'Sheet1(RPA-Chat Create)');
  XLSX.writeFile(workbook, 'RPAChat_Data.xlsx');
}

const { Option } = Select;

interface RPAEchartsProps {
  content: string;
}

export default function RPAEchartsOrTable({ content }: RPAEchartsProps) {
  const [selectedView, setSelectedView] = useState('Table'); // 默认值为 Table
  const [isModalVisible, setIsModalVisible] = useState(false); // 控制 Modal 的可见性
  const [shouldRender, setShouldRender] = useState(false); // 控制 ECharts 渲染
  const chartRef = useRef<any>(null);

  // 图表配置
  const getOption = (chartType: string) => ({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      confine: true,
    },
    legend: {
      top: '5%',
      left: 'center',
    },
    grid: {
      top: '15%',
      left: '10%',
      right: '10%',
      bottom: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: 'Direct',
        type: chartType,
        data: [320, 332, 301, 334, 390, 330, 320],
      },
      {
        name: 'Email',
        type: chartType,
        data: [120, 132, 101, 134, 90, 230, 210],
      },
    ],
  });

  const handleChange = (value: string) => {
    setSelectedView(value); // 更新选择值
  };

  const downloadChart = () => {
    if (selectedView !== 'Table') {
      if (chartRef.current) {
        const echartsInstance = chartRef.current.getEchartsInstance();
        const imageUrl = echartsInstance.getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#fff',
        });

        const link = document.createElement('a');
        link.href = imageUrl;
        link.download = 'RPAEcharts-image.png';
        link.click();
      }
    } else {
      JsonToExcel(content);
    }
  };

  // 打开/关闭 Modal
  const openModal = () => {
    setIsModalVisible(true);
    setTimeout(() => setShouldRender(true), 300); // 延迟渲染图表
  };
  const closeModal = () => {
    setShouldRender(false); // 停止渲染图表
    setIsModalVisible(false);
  };

  return (
    <div style={{ width: '650px' }}>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          marginBottom: '10px',
        }}
      >
        <Select defaultValue="Table" onChange={handleChange}>
          <Option value="Table">数据表</Option>
          <Option value="bar">柱状图</Option>
          <Option value="line">折线图</Option>
          <Option value="scatter">散点图</Option>
        </Select>

        <div style={{ display: 'flex', gap: '10px' }}>
          <Tooltip title="下载文件">
            <Button type="dashed" onClick={downloadChart} icon={<Download size={18} />} />
          </Tooltip>
          <Tooltip title="最大化">
            <Button type="dashed" onClick={openModal} icon={<Maximize size={18} />} />
          </Tooltip>
        </div>
      </div>

      {/* 动态输出内容 */}
      <TableAndCharts h="350px" w="100%" />

      {/* Modal */}
      <Modal
        title="图表"
        open={isModalVisible}
        onCancel={closeModal}
        footer={null}
        width="70%"
        bodyStyle={{ 
          padding: 0, // 去掉 padding 并设置高度
          height: selectedView === 'Table' ? '100%' : '60vh',
          maxHeight: '80vh',
          overflow: selectedView === 'Table'? 'auto' : 'hidden'
        }}
        style={{
          maxHeight: '90vh', // 设置 Modal 最大高度
          overflowY: selectedView === 'Table'? 'auto' : 'hidden' // 允许滚动
        }}
      >
        {/* 只有在 Modal 完全显示后才渲染 ECharts */}
        {shouldRender && <TableAndCharts h="100%" w="100%" />}
      </Modal>
    </div>
  );

  // 将Table组件 与 Echarts 判断封装为一个组件
  function TableAndCharts({ h, w }: { h: string; w: string }) {
    return selectedView === 'Table' ? (
      <RPATable content={content} />
    ) : (
      <ReactEcharts
        ref={chartRef}
        option={getOption(selectedView)}
        style={{ width: w, height: h }}
        opts={{ renderer: 'canvas', devicePixelRatio: 3 }}
      />
    );
  }
}